package com.study.intercepter;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class LoginIntercepter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        if (requestURI.equals("/user/login") || requestURI.equals("/user/sign")){
            return true;
        }

        //获取登录用户的session
        Object loginUser=request.getSession().getAttribute("userInfo");

        //session不存在，即用户尚未登录
        if(Objects.isNull(loginUser)){
            request.setAttribute("msg","请先登录");
            //返回首页
            request.getRequestDispatcher("/login.html").forward(request,response);
            return false;
        }else {
            return true;
        }

    }

}
